#include "TransformedVertexBuffer.h"
#include "..\utils\Log.h"

namespace ds {

TransformedVertexBuffer::TransformedVertexBuffer(D3DPRIMITIVETYPE primitiveType,uint32 maxVertices,bool dynamic) 
	: VertexBuffer(primitiveType,dynamic) , m_MaxVertices(maxVertices) {
		m_FVF = D3DFVF_XYZRHW | D3DFVF_TEX1;	
		m_vertexSize = sizeof(TransformedVertex);
		IDirect3DDevice9 * pDevice = gEngine->getDevice();
		D3DPOOL pool = m_Dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED; 
		DWORD usage = m_Dynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : D3DUSAGE_WRITEONLY; 		
		LOG(logINFO) << "creating new transformed textured vertex buffer size: " << m_MaxVertices << " dynamic: "<< dynamic;
		HR(pDevice->CreateVertexBuffer( m_MaxVertices * sizeof( TransformedVertex),usage,m_FVF ,pool, &vertexBuffer, NULL ));
}

TransformedVertexBuffer::~TransformedVertexBuffer() {
	Release();
}

void TransformedVertexBuffer::addVertex(float x,float y,float z,float u,float v) {
	if ( m_Vertices.size() <= m_MaxVertices ) {
		TransformedVertex tv;
		tv.x = x;
		tv.y = y;
		tv.z = z;
		tv.tu = u;
		tv.tv = v;	
		m_Vertices.push_back(tv);
	}
	else {
		LOGC(logERROR,"TransformedVertexBuffer") << "addVertex : maximum exceeded";
	}
}

void TransformedVertexBuffer::clear() {
	m_Vertices.clear();
}

bool TransformedVertexBuffer::createBuffer() {	
	size_t total = m_Vertices.size();	
	if ( total > 0 ) {		
		TransformedVertex *pVertices;
		HR(vertexBuffer->Lock( 0, 0, ( void** )&pVertices, 0 ));	
		for ( size_t i = 0; i < total; ++i ) {		
			pVertices->x = m_Vertices[i].x;
			pVertices->y = m_Vertices[i].y;
			pVertices->z = m_Vertices[i].z;
			pVertices->rwh = 1.0f;
			pVertices->tu = m_Vertices[i].tu;
			pVertices->tv = m_Vertices[i].tv;									
			pVertices++;
		}
		HR(vertexBuffer->Unlock());
	}
	m_numVertices = total;
	return true;
}

}

